package com.polaris.live.popup.party

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.R.color
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupRoomInfoAnchorBinding
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.net.liveService
import com.polaris.live.resp.back_resp.PartyRoomInfoResp
import com.polaris.live.resp.go_resp.ChangeRoomNameRequest
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.fragment.roomInfo.AnchorRoomInfoFragment
import com.polaris.live.ui.party.fragment.roomInfo.MemberFragment
import com.polaris.live.ui.party.fragment.roomInfo.RoomInfoFollowMemberFragment
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.transformRounded

/**
 * RoomInfoAnchorPopup房主查看房间信息
 *
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class RoomInfoAnchorPopup : DialogFragment() {

    private lateinit var mBinding: PopupRoomInfoAnchorBinding

    private val mLiveId by lazy { arguments?.getLong("liveId") ?: 0 }
    private val mUserId by lazy { arguments?.getLong("userId") ?: 0 }
    private val mRoomId by lazy { arguments?.getString("roomId") ?: "" }
    private val mVipLevel by lazy { arguments?.getLong("vipLevel") }
    private val mRoomTheme by lazy { arguments?.getString("roomTheme") ?: "" }

    private var mPartyRoomInfoResp: PartyRoomInfoResp? = null

    private var mOnClickListener: ((userId: Long) -> Unit)? = null
    private var mOnNameModifyListener: ((name: String) -> Unit)? = null

    private val mViewModel by viewModels<BaseViewModel>()

    private val mAnchorRoomInfoFragment by lazy {
        AnchorRoomInfoFragment()
    }
    private val mRoomInfoFollowMemberFragment by lazy {
        RoomInfoFollowMemberFragment().apply {
            arguments = bundleOf(
                "userId" to mUserId
            )
            setListener {
                dismiss()
                mOnClickListener?.invoke(it)
            }
        }
    }
    private val mMemberFragment by lazy {
        MemberFragment().apply {
            arguments = bundleOf(
                "roomId" to mRoomId,
                "anchor" to true
            )
            setListener {
                dismiss()
                mOnClickListener?.invoke(it)
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = PopupRoomInfoAnchorBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            setWindowAnimations(R.style.BottomDialogAnimation)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .transparentNavigationBar()
            .init()
        initView()
        val bottomView = mBinding.bottom
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), android.R.style.Theme_Light_NoTitleBar_Fullscreen)
        val window = dialog.window
        window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return dialog
    }

    fun initView() {
        val mFragments = arrayListOf(mAnchorRoomInfoFragment, mRoomInfoFollowMemberFragment, mMemberFragment)
        mBinding.viewpager2.adapter = ViewPagerAdapter(mFragments, this)
        mBinding.viewpager2.currentItem = 0
        initListener()
        getData()

        val themeData = AppConfigManager.getUserTheme(mRoomTheme)
        themeData?.let { theme ->
            mBinding.consCenter.setBackgroundResource(0)
            mBinding.ivRoomInfoBack.visibility = View.VISIBLE
            mBinding.ivRoomInfoBack.shapeDrawableBuilder
                .setSolidGradientColors(Color.parseColor(theme.listStartColor), Color.parseColor(theme.listEndColor))
                .intoBackground()
            Glide.with(requireContext()).load(ImageUtils.imgPath(theme.listIcon)).into(mBinding.ivSkinIcon)
            mBinding.ivSkinIcon.alpha = theme.listAlpha?.div(100f) ?: 0.3f
        }
    }

    private fun getData() {
        mViewModel.requestLoading(
            { liveService.getPartyRoomInfo(mLiveId) },
            {
                mPartyRoomInfoResp = it
                setDataView(it)
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    private fun setDataView(mPartyRoomInfoResp: PartyRoomInfoResp) {
        mBinding.apply {
            widgetLoading.visibility = View.GONE
            mainLl.visibility = View.VISIBLE
            Glide.with(requireContext())
                .load(ImageUtils.imgPath(mPartyRoomInfoResp.cover))
                .transformRounded(6.autoDp)
                .into(roomImg)
            roomName.text = mPartyRoomInfoResp.roomName
            roomId.text = StringUtils.getString(string.id, mPartyRoomInfoResp.roomNumber)

            followersNumber.text = "${getString(string.followers_people)}:${mPartyRoomInfoResp.follower}"
            memberNumber.text = "${getString(string.member)}:${mPartyRoomInfoResp.member}"

            mAnchorRoomInfoFragment.setDataView(mPartyRoomInfoResp)
            mRoomInfoFollowMemberFragment.setCount(mPartyRoomInfoResp.follower)

            roomFrame.setRoomFrame(mPartyRoomInfoResp.user.roomFrame)
        }
    }

    private fun initListener() {
        mBinding.root.setOnClickListener {
            dismiss()
        }
        mBinding.mainLl.setOnClickListener {
        }

        mBinding.informationLl.setOnClickListener {
            setTab(0)
            mBinding.viewpager2.currentItem = 0
        }
        mBinding.followersLl.setOnClickListener {
            setTab(1)
            mBinding.viewpager2.currentItem = 1
        }
        mBinding.memberLl.setOnClickListener {
            setTab(2)
            mBinding.viewpager2.currentItem = 2
        }

        mBinding.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setTab(position)
            }
        })
        mBinding.nameFbl.setOnClickListener {
            showRoomNamePopup()
        }
    }

    private fun setTab(index: Int) {
        when (index) {
            0 -> {
                mBinding.informationLine.visibility = View.VISIBLE
                mBinding.followersLine.visibility = View.GONE
                mBinding.memberLine.visibility = View.GONE
                mBinding.textInformation.setTextColor(ColorUtils.getColor(R.color.white))
                mBinding.textFollowers.setTextColor(ColorUtils.getColor(color.color_80ffffff))
                mBinding.textMember.setTextColor(ColorUtils.getColor(color.color_80ffffff))
            }

            1 -> {
                mBinding.informationLine.visibility = View.GONE
                mBinding.followersLine.visibility = View.VISIBLE
                mBinding.memberLine.visibility = View.GONE
                mBinding.textInformation.setTextColor(ColorUtils.getColor(color.color_80ffffff))
                mBinding.textFollowers.setTextColor(ColorUtils.getColor(R.color.white))
                mBinding.textMember.setTextColor(ColorUtils.getColor(color.color_80ffffff))
            }

            2 -> {
                mBinding.informationLine.visibility = View.GONE
                mBinding.followersLine.visibility = View.GONE
                mBinding.memberLine.visibility = View.VISIBLE
                mBinding.textInformation.setTextColor(ColorUtils.getColor(color.color_80ffffff))
                mBinding.textFollowers.setTextColor(ColorUtils.getColor(color.color_80ffffff))
                mBinding.textMember.setTextColor(ColorUtils.getColor(R.color.white))
            }
        }

    }

    /**
     * 显示房间名修改
     */
    private fun showRoomNamePopup() {
        XPopup.Builder(context)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(RoomNameMessagePopup(requireContext(), mPartyRoomInfoResp?.roomName) { name ->
                roomNameUpdate(name)
            })
            .show()
    }

    private fun roomNameUpdate(name: String) {
        mViewModel.request(
            { liveService.changeRoomName(ChangeRoomNameRequest(name)) }, {
                mBinding.roomName.text = name
                mOnNameModifyListener?.invoke(name)
                ToastGravity.showGravity(string.modified_successfully)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            }
        )
    }

    companion object {

        fun show(
            context: Fragment,
            liveId: Long,
            userId: Long,
            roomId: String,
            vipLevel: Long? = null,
            roomTheme: String? = null,
            click: ((userId: Long) -> Unit)?,
            nameModify: ((name: String) -> Unit)?,
        ) {
            val fragmentManager = context.parentFragmentManager
            RoomInfoAnchorPopup()
                .apply {
                    arguments = bundleOf(
                        "liveId" to liveId,
                        "userId" to userId,
                        "roomId" to roomId,
                        "vipLevel" to vipLevel,
                        "roomTheme" to roomTheme
                    )
                    mOnClickListener = click
                    mOnNameModifyListener = nameModify
                }.show(fragmentManager, "RoomInfoAnchorPopup")

        }

    }
}